<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2016/12/7
 * Time: 11:59
 */

namespace App\Services\PrintService;


use App\Services\Tool\Svg\SVGFont;
use Illuminate\Support\Facades\DB;

class PrintTool
{
    /***
     * 查看产品是不是存在
     * @param $product_id
     * @return bool
     */
    public static function getProductExistByProductId($product_id){
        $num=DB::table('products')
            ->where('product_id',$product_id)
            ->count();
        return ($num===0)?false:true;
    }
    /**
     * 生成svg文件
     * @param $svg_param
     * @param int $scale  放大倍数
     * @return string
     * @throws \Exception
     */
    public function generateSvg($svg_param,$scale=1){
        $svg = new SVGFont();
        //dd($svg_param);
        $arr = $svg->get_array_to_use($svg_param,$scale);
        $svg->set_font_family($arr['font_family']);
        $svg->set_font_size($arr['font_size']);
        $svg->set_font_newline($arr['newline']);
        $svg->set_font_fill($arr['fill']);
        $svg->addText($arr['text']);
        $svg->addAttribute("width", $svg->get_text_width()."px");
        $svg->addAttribute("height", $svg->get_text_height() . "px");
        $svg_path =  'svg' . DIRECTORY_SEPARATOR .date('Ym') .DIRECTORY_SEPARATOR ;
        $svg_name=md5(date('ymdhis').rand(1, 1000)) . ".svg";
        $folder=public_path("images".DIRECTORY_SEPARATOR.'product_print_images').DIRECTORY_SEPARATOR.$svg_path;
        @$this->mkFolder($folder);
        $svg_absolute_path=$folder.$svg_name;
        $result = $svg->asXML($svg_absolute_path);
        return $svg_path.$svg_name;
    }

    /**
     * 创建文件夹
     * @param $path
     */
    private function mkFolder($path)
    {
        try{
            if(!is_readable($path))
            {
                is_file($path) or mkdir($path,0666);
            }
        }catch (\Exception $e){
            Log::info('PrintService mkFolder 出现异常');
            Log::info($e);
            return false;
        }
    }
}